#!/usr/bin/env python3
# coding: utf-8
# from typing import Dict, Union
from datetime import datetime, timedelta
import freeswitch
import time
import random
import demjson
import json

import pycurl
from io import BytesIO

try:
    # python 3
    from urllib.parse import urlencode
except ImportError:
    # python 2
    from urllib import urlencode

# 注：不支持市面上SIP客户端接入，仅用于扩展了相关SIP头的webrtc或SIP客户端接入

# 此运行在python2 上面，编码方面不太一样
# 使用集成商的gateway
# lastCallInfo key 更改为:LastCallInfo:客户号码,并使用http调用存储
# TODO##############redis-py-cluster 2.0不支持3.2的redis集群，等待2.1版本#######################
###

def handler(session, args):  # args is string
    session.setAutoHangup(False)
    uuid = session.getVariable("uuid")

    if args is None:
        freeswitch.console_log("info", "call %s has no target call number in args param\n" % uuid)
        session.hangup("UNALLOCATED_NUMBER")
        return

    freeswitch.console_log("info", "call %s args string is: %s \n" % (uuid, args))

    X_uuid = session.getVariable("sip_h_X-uuid")
    X_create_user_id = session.getVariable("sip_h_X-create_user_id")
    X_city = session.getVariable("sip_h_X-city")

    if X_create_user_id is None or X_city is None or X_uuid is None:
        freeswitch.console_log("info", "X_uuid and X_create_user_id and X_uuid is required !")
        session.hangup("UNALLOCATED_NUMBER")
        return

    freeswitch.console_log("info", "city type str: %s \n" % isinstance(X_city, str))
    freeswitch.console_log("info", "X_create_user_id type str: %s \n" % isinstance(X_create_user_id, str))

    X_uuid = X_uuid.strip()
    X_create_user_id = X_create_user_id.strip()
    X_city = X_city.strip()

    freeswitch.consoleLog("info", "call %s extend params: X_uuid: %s, X_create_user_id: %s, X_city: %s \n" %
                          (uuid, X_uuid, X_create_user_id, X_city))
    # X_main_call_phone: 13724059427',
    # X_target_call_phone: 13523236314',
    # X_show_num: 18600000000',

    X_where_from = session.getVariable("sip_h_X-where_from")
    X_page_from = session.getVariable("sip_h_X-page_from")
    X_enroll_num = session.getVariable("sip_h_X-enroll_num")
    # X_reg_psw = session.getVariable("sip_h_X-reg_psw")
    X_data_id = session.getVariable("sip_h_X-data_id")
    X_customer_name = session.getVariable("sip_h_X-customer_name")
    X_customer_no = session.getVariable("sip_h_X-customer_no")
    X_project_name = session.getVariable("sip_h_X-project_name")
    # X_project_no = session.getVariable("sip_h_X-project_no")
    # X_token = session.getVariable("sip_h_X-token")
    X_package_id = session.getVariable("sip_h_X-package_id")
    X_call_task_id = session.getVariable("sip_h_X-call_task_id")
    freeswitch.consoleLog("info", "call %s extend params:X_where_from: %s,X_page_from: %s,X_enroll_num: %s,X_data_id: "
                                  "%s,X_customer_name: %s,X_customer_no: %s,X_project_name: %s,X_package_id: %s,"
                                  "X_call_task_id: %s \n" %
                          (uuid, X_where_from, X_page_from, X_enroll_num, X_data_id, X_customer_name, X_customer_no,
                           X_project_name, X_package_id, X_call_task_id))
    post_data = {
        'cityId': X_city,
        'dataId': (X_data_id if X_data_id is not None else "-1"),
        'enrollNum': (X_enroll_num if X_enroll_num is not None else "-1"),
        'userId': X_create_user_id,
        'direct_call': True,
        'mainCallPhone': session.getVariable("sip_from_user"),
        'targetCallPhone': args,
        'commitTime': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        'callTaskId': (X_call_task_id if X_call_task_id is not None else "-1"),
        'packageId': (X_package_id if X_package_id is not None else "-1"),
        'whereFrom': (X_where_from if X_where_from is not None else "-1"),
        'pageFrom': (X_page_from if X_page_from is not None else "-1"),
        'projectName': (X_project_name if X_project_name is not None else "-1"),
        'customerName': (X_customer_name if X_customer_name is not None else "-1"),
        'customerNo': (X_customer_no if X_customer_no is not None else "-1")
    }
    try:

        # buffer = BytesIO()
        c = pycurl.Curl()
        url = "https://aicall.ihk.cn:9443/fsm/lastCallInfo/add"
        c.setopt(c.URL, url)
        c.setopt(pycurl.SSL_VERIFYPEER, 1)
        c.setopt(pycurl.SSL_VERIFYHOST, 2)
        # <TIPS>windows 要指定证书的路径不然会出现(77, "SSL: can't load CA certificate file E:\\curl\\ca-bundle.crt")
        # 证书路径就在curl下载的压缩包里面。mac/linux下面可以注释掉。
        c.setopt(pycurl.CAINFO, "/usr/local/freeswitch/certs/cafile.pem")
        # post_data = {'customerPhone': '13724059427'}
        # Form data must be provided already urlencoded.
        postfields = urlencode(post_data)
        # Sets request method to POST,
        # Content-Type header to application/x-www-form-urlencoded
        # and data to send in request body.
        c.setopt(c.POSTFIELDS, postfields)
        # c.setopt(c.WRITEDATA, buffer)
        c.perform()
        c.close()
        # body = buffer.getvalue()
        # Body is a byte string.
        # We have to know the encoding in order to print it to a text file
        # such as standard output.
        # rs = body.decode('utf8')
        # if rs is not None:
        #     rs = demjson.decode(rs)
        # if rs['code'] != -1:

        session.setVariable("continue_on_fail", "false")
        session.setVariable("hangup_after_bridge", "true")
        session.setVariable("jitterbuffer_msec", "260:400:20")
        # session.setVariable("rtp_jitter_buffer_during_bridge","true")
        session.execute("export", "session_id=${uuid}")
        session.execute("export", "call_timeout=60")
        # TODO ????勾无效？
        session.setHangupHook("hangup_hook")
        # save record file
        today = time.strftime("%Y%m%d", time.localtime())

        record_save_base_paths = ["/cloudcall_file/rec_20050/freeswitchRecordFile/",
                                  "/cloudcall_file/rec_20051/freeswitchRecordFile/"]
        path = random.choice(record_save_base_paths) + today + "/" + uuid + ".wav"
        freeswitch.console_log("info", "choice path: %s" % path)
        session.execute("export", "nolocal:execute_on_answer=record_session " + path)

        call_str = "sofia/internal/%s@39.108.194.175:5060" % args
        freeswitch.console_log("info", "bridge string is: %s \n" % call_str)
        # session.execute("bridge", "user/%s" % args)
        session.execute("bridge", call_str)
        session.hangup()
    except Exception as err:
        freeswitch.console_log("err", "call %s exception,msg: %s \n" % (uuid, err))
        session.hangup("ORIGINATOR_CANCEL")


def hangup_hook(uuid):
    freeswitch.console_log("info", "myHangupHook, uuid: %s!!\n" % uuid)
    return "Result"
